﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Web;
using Project.Core.Config.Common.Filter;
using Project.Core.Config.Common.Utils;
using Project.Core.Config.Config.Autofac;
using Project.Core.Config.Config.Cache;
using Project.Core.Config.Config.DbConnect;
using Project.Core.Config.Config.Jwt;
using Project.Core.Config.Config.Mq;
using Project.Core.Config.Config.Swagger;
using System.Text.Json.Serialization;

namespace Project.Core.Config {
    public static class BuilderExtensions {
        public static void AddBuilder(this WebApplicationBuilder builder) {
            //添加日志
            builder.Host.UseNLog();
            // 配置日志
            builder.Services.AddSingleton(new AppHelper(
                builder.Configuration, 
                builder.Services.BuildServiceProvider().GetRequiredService<ILogger<AppHelper>>())
            );

            //配置过滤器，和json
            builder.Services.AddControllers(option => {
                option.Filters.Add<ExceptionFilter>();
                option.Filters.Add<AuthorizeFilter>();
            }).AddNewtonsoftJson().AddJsonOptions(option => {
                option.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); //显示枚举注释
            });

            //配置跨域访问问题
            builder.Services.AddCors(
                options => options.AddPolicy("Cors", p => p
                    .AllowAnyOrigin()
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                )
            );

            //配置autofac
            builder.AddAutofacBuilder();

            //配置数据库
            builder.AddDbBuilder();

            //配置缓存
            builder.AddCacheBuilder();

            //配置JWT
            builder.AddJwtBuilder();

            //配置Mq
            builder.AddMqBuilder();

            //配置Swagger
            builder.AddSwaggerBuilder();
        }
    }
}